package com.shiguiwu.springboot3.service;

import com.shiguiwu.springboot3.dto.response.ReplyResponse;
import com.shiguiwu.springboot3.entity.ChatMessage;
import com.shiguiwu.springboot3.mapper.ChatMessageMapper;
import com.shiguiwu.springboot3.util.MemberContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 对话上下文
 * @author: stone
 * @date: Created by 2025/10/19 11:29
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.service
 */
@Service
public class ConversationService {

    @Autowired
    private ChatService chatService;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    public void appendMessage(String sessionId, String role, String content) {

    }

    public List<String> getRecentContext(String sessionId, int limit) {
        return null;
    }

    @Transactional
    public ReplyResponse dialogBot(String message, Long sessionId) {
        String chat = chatService.chat(MemberContextUtils.getCurrentUserId(), message);
        boolean success = this.saveDialogBot(message, sessionId, chat);
        if(success) {
            return new ReplyResponse("bot", chat);
        }
        return null;
    }

    private boolean saveDialogBot(String message, Long sessionId, String chat) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContent(message);
        chatMessage.setCreatedAt(LocalDateTime.now());
        chatMessage.setIsRead((byte) 1);
        chatMessage.setSessionId(sessionId);
        chatMessage.setFromUserId(MemberContextUtils.getCurrentUserId());
        chatMessage.setToUserId(-1L); //机器人


        ChatMessage chatBot = new ChatMessage();
        chatBot.setContent(chat);
        chatBot.setCreatedAt(LocalDateTime.now());
        chatBot.setIsRead((byte) 1);
        chatBot.setSessionId(sessionId);
        chatBot.setFromUserId(-1L);
        chatBot.setToUserId(MemberContextUtils.getCurrentUserId()); //机器人

        int batched = chatMessageMapper.batchInsert(List.of(chatBot, chatMessage));
        return batched == 2;
    }

}
